import sys
import asyncio
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QThread, pyqtSignal
import concurrent.futures

#AsyncWorker类，继承自QThread，所以它本身就是用一个线程
class AsyncWorker(QThread):
    """异步任务执行线程"""
    result_ready = pyqtSignal(str)  # 结果信号

    def run(self):
        """线程启动时执行，线程启动后会启动调用run方法，在这里重写run方法"""
        loop = asyncio.new_event_loop()  # 创建独立事件循环
        asyncio.set_event_loop(loop)
        try:
            # 运行协程并获取结果
            result = loop.run_until_complete(self.async_task(10))
            self.result_ready.emit(result)
        finally:
            loop.close()

    async def async_task(self,i):
        """模拟异步操作（如网络请求）"""
        await asyncio.sleep(1)  # 非阻塞等待3秒
        print("异步任务开始。。。")
        m=0
        while True:
            await asyncio.sleep(1)
            print(m)
            m=m+1
        return "异步任务完成！"

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.thread = None

    def init_ui(self):
        self.setWindowTitle("协程+PyQt示例")
        self.button = QPushButton("启动异步任务")
        self.button.clicked.connect(self.start_task)
        
        layout = QVBoxLayout()
        layout.addWidget(self.button)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    #用法一：正常
    # def start_task(self):
    #     """启动异步任务"""
    #     if self.thread is None or not self.thread.isRunning():
    #         self.thread = AsyncWorker()
    #         self.thread.result_ready.connect(self.on_task_done)
    #         self.thread.start()

    # #用法二：正常
    # def start_task(self):
    #     """启动异步任务"""
    #     #if self.thread is None or not self.thread.isRunning():
    #     if True:
    #         self.thread = AsyncWorker()
    #         self.thread.result_ready.connect(self.on_task_done)
    #         self.thread.start()

    # #用法三：正常
    # def start_task(self):
    #     """启动异步任务"""
    #     #if self.thread is None or not self.thread.isRunning():
    #     if True:
    #         self.thread = AsyncWorker()
    #         #self.thread.result_ready.connect(self.on_task_done)
    #         self.thread.start()

    #用法四：正常
    def start_task(self):
        if True:
            # print(self.thread)
            # print(thread)
            self.thread = AsyncWorker()
            self.thread.start()

    def on_task_done(self, result):
        """处理异步结果"""
        print("异步结果是："+result)
        self.button.setEnabled(True)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyleSheet("""
        * {
            font-family: "微软雅黑", "Consolas";
            font-size: 10pt;
        }
        QTableWidget {
            background-color: white;
            border: 1px solid #E0E0E0;
            margin-top: 10px;
        }
        /* 移除特定控件的字体设置 */
        QLineEdit, QTableWidget, QLabel {
            min-height: 25px;
            padding: 2px 5px;
        }
        QTableWidget {
            min-width: 800px;
        }
        QLineEdit {
            min-width: 150px;
        }
        QComboBox {
            min-width: 200px;
        }
    """)
    window = MainWindow()
    window.setGeometry(500,300,300,350)
    window.show()
    sys.exit(app.exec_())